package com.hifar.test.api.util;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @ClassName TransferUtil
 * @Description 请求头改造
 * @Author ZY.G
 * @Time 2025/8/19 14:11
 * @Version 1.0
 */
public class TransferUtil {

    private static final String MD5 = "MD5";
    private static final String RSA_PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJcpZT66UFqRaYD5HY/Oh/FyXEFJbJ25pQnAPQEaVh0GjRuHgAvg3Sj6dPXNJcNtOOxhNA2sJiRKW1x8lw1QoT8CAwEAAQ==";
    private static final String RSA_PRIVATE_KEY = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAlyllPrpQWpFpgPkdj86H8XJcQUlsnbmlCcA9ARpWHQaNG4eAC+DdKPp09c0lw2047GE0DawmJEpbXHyXDVChPwIDAQABAkAPsh+uLMBtNw4iczuLlCFvg7VqngomMoGdipWLCMYKS1v/MfmAWzuBPMwV2XEgyuBa70BV0ykD0W+A6S8QAQfJAiEAxalpxCXYkXBhSUQ0UqMjcmoFDbNusCyr9UhxgX/ZA9UCIQDDxpxCab94SEsF5kgraPf8PKDezCusQLvhWBIoWvDewwIgOOjXB99xpCY8DHEzs1s/GHEH9XLk+ppSBDQQYh2iKOUCIFCTRKq81TYPIvmJnrhnGnFxDpDEHVFmzyzez5JWY357AiEAhCR7AMuAXJgm/1wHS1vRPiHIWTT9HiEZv2UaMKv5ZlY=";
    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return PublicKey
     * @throws Exception
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return PrivateKey
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 使用公钥加密
     *
     * @param data 数据
     * @return 加密后的数据（Base64 编码）
     * @throws Exception
     */
    public static String encryptRSA(String data) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(RSA_PUBLIC_KEY));
        return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
    }

    /**
     * 使用私钥解密
     *
     * @param encryptedData 加密数据（Base64 编码）
     * @return 解密后的数据
     * @throws Exception
     */
    public static String decryptRSA(String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(RSA_PRIVATE_KEY));
        return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedData)));
    }

    // MD5 工具加密
    public static String md5(String input){
        try {
            MessageDigest md = MessageDigest.getInstance(MD5);
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws Exception {
        String password = encryptRSA("hifar");
        System.out.println("RSA加密密码：" + password);
        String base64 = "demo:" + password;
        System.out.println("base64加密前字符串：" + base64);
        String base64Str = Base64.getEncoder().encodeToString(base64.getBytes());
        System.out.println("base64加密后字符串：" + base64Str);
        String base64Dec = new String(Base64.getDecoder().decode(base64Str), StandardCharsets.UTF_8);
        System.out.println("base64解密后字符串：" + base64Dec);
        System.out.println("RSA解密密码：");
        System.out.println(decryptRSA(password));
    }

}
